import { ref } from 'vue'
import { defineStore } from 'pinia'
import {ElMessage} from "element-plus";

export const useUserStore = defineStore('user', () => {
    const user = ref({})
    const token = ref('')

    // 设置用户信息
    const setUserInfo = (data) => {
        user.value = data
        user.value.id ? localStorage.setItem('currentUserId', user.value.id) : ElMessage.error('未获取到当前用户id')
    }

    // 清除用户信息
    const clearUserInfo = () => {
        user.value = {}
        localStorage.getItem('currentUserId') ? localStorage.removeItem('currentUserId') : ''
    }

    // 设置token
    const setToken = (userToken) => {
        token.value = userToken
        token.value ? localStorage.setItem('token', token.value) : ElMessage.error('未获取到当前用户登录用户验证token')
    }
    // 清除token
    const clearToken = () => {
        token.value = ''
        localStorage.getItem('token') ? localStorage.removeItem('token') : ''
    }

    return {user, setUserInfo, clearUserInfo, setToken, clearToken}
})
